package com.kawins.util.encrypt;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import java.io.IOException;
import java.security.SecureRandom;

/**
 * @author rankai
 *         createTime 2018-01-2018/1/2 13:54
 */
public final class DES {

    private final static String DES = "DES";
    private final static String ENCODE = "utf-8";
    private final static String DEFAULT_KEY = "KawinsDE";

    /**
     * 默认key加密
     *
     * @param str
     * @return
     * @throws Exception
     */
    public static String encryptDES(String str) throws Exception {
        byte[] bt = encrypt(str.getBytes(ENCODE), DEFAULT_KEY.getBytes(ENCODE));
        return java.util.Base64.getEncoder().encodeToString(bt);
    }

    /**
     * 默认key解密
     *
     * @param str
     * @return
     * @throws IOException
     * @throws Exception
     */
    public static String decryptDES(String str) {
        if (str == null) {
            return null;
        }
        return build(str, DEFAULT_KEY);
    }


    /**
     * 根据键值进行加密
     *
     * @param str
     * @param key 加密Key,只有前8位有效
     * @return
     * @throws Exception
     */
    public static String encryptDES(String str, String key) {
        try {
            byte[] bt = encrypt(str.getBytes(ENCODE), buildKey(key).getBytes(ENCODE));
            return java.util.Base64.getEncoder().encodeToString(bt);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 根据键值进行解密
     *
     * @param str
     * @param key 加密键byte数组
     * @return
     * @throws IOException
     * @throws Exception
     */
    public static String decryptDES(String str, String key) {
        if (str == null) {
            return null;
        }
        return build(str, buildKey(key));
    }

    /**
     * 构建Key
     *
     * @param key
     * @return
     */
    private static String buildKey(String key) {
        int length = key.length();
        if (length < 8) {
            StringBuffer sb = new StringBuffer(key);
            for (int i = 0; 8 - length > i; i++) {
                sb.append(i);
            }
            return sb.toString();
        }
        return key;
    }

    /**
     * @param str
     * @param key
     * @return
     */
    private static String build(String str, String key) {
        try {
            byte[] buf = java.util.Base64.getDecoder().decode(str);
            byte[] bt = decrypt(buf, key.getBytes(ENCODE));
            return new String(bt, ENCODE);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * Description 根据键值进行加密
     *
     * @param data
     * @param key  加密键byte数组
     * @return
     * @throws Exception
     */
    private static byte[] encrypt(byte[] data, byte[] key) throws Exception {
        // 生成一个可信任的随机数源
        SecureRandom sr = new SecureRandom();
        // 从原始密钥数据创建DESKeySpec对象
        DESKeySpec dks = new DESKeySpec(key);
        // 创建一个密钥工厂，然后用它把DESKeySpec转换成SecretKey对象
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES);
        SecretKey secretKey = keyFactory.generateSecret(dks);
        // Cipher对象实际完成加密操作
        Cipher cipher = Cipher.getInstance(DES);
        // 用密钥初始化Cipher对象
        cipher.init(Cipher.ENCRYPT_MODE, secretKey, sr);
        return cipher.doFinal(data);
    }

    /**
     * Description 根据键值进行解密
     *
     * @param data
     * @param key  加密键byte数组
     * @return
     * @throws Exception
     */
    private static byte[] decrypt(byte[] data, byte[] key) throws Exception {
        // 生成一个可信任的随机数源
        SecureRandom sr = new SecureRandom();
        // 从原始密钥数据创建DESKeySpec对象
        DESKeySpec dks = new DESKeySpec(key);
        // 创建一个密钥工厂，然后用它把DESKeySpec转换成SecretKey对象
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES);
        SecretKey SecretKey = keyFactory.generateSecret(dks);
        // Cipher对象实际完成解密操作
        Cipher cipher = Cipher.getInstance(DES);
        // 用密钥初始化Cipher对象
        cipher.init(Cipher.DECRYPT_MODE, SecretKey, sr);
        return cipher.doFinal(data);
    }

    public static void main(String[] args) throws Exception {
        String str = "kawins";
        DES des = new DES();
        String s = des.encryptDES(str, "12345678");
        System.out.println(s);
        String s1 = des.decryptDES(s, "12345678");
        System.out.println(s1);
    }
}
